package cn.zwk.common.autoconfig;

import cn.zwk.common.interceptor.GlobalMybatisInterceptor;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;

import java.util.Map;

@ConditionalOnClass(
        name = {"com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration",
                "com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor"
        }
)

public class CommonAutoConfiguration implements ApplicationContextAware {
    private ApplicationContext context;

    /**
     * myBatis自动填充
     * @return
     */
    @ConditionalOnMissingBean(MetaObjectHandler.class)
    @ConditionalOnProperty("common.global.mybatis-interceptor")
    @Bean
    public GlobalMybatisInterceptor globalMybatisInterceptor() {
        return new GlobalMybatisInterceptor();
    }

    /**
     * myBatis分页插件
     * @return
     */
    @ConditionalOnProperty("common.global.mybatis-plus-interceptor")
    @Bean("globalPlusInterceptor")
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        try {
            Map<String, MybatisPlusInterceptor> interceptorMap = context.getBeansOfType(MybatisPlusInterceptor.class);
            MybatisPlusInterceptor interceptor = interceptorMap.values().stream().reduce(new MybatisPlusInterceptor(), (res, item) -> {
                res.getInterceptors().addAll(item.getInterceptors());
                return res;
            });
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
            return interceptor;
        } catch (Exception e) {
            System.out.println(666);
        }
        return new MybatisPlusInterceptor();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
